package com.zzq.util;


import com.zzq.config.CustomMultipartFile;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageUtil {
    public static File getImageFile(String imageName) throws IOException, URISyntaxException {
        ClassLoader classLoader = ImageUtil.class.getClassLoader();
        URL resourceURL = classLoader.getResource("static/images/" + imageName);

        if (resourceURL == null) {
            throw new IOException("Image not found: " + imageName);
        }

        Path imagePath = Paths.get(resourceURL.toURI());
        return imagePath.toFile();
    }


    //File 转 MultipartFile
    public static MultipartFile convertFileToMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
    // MultipartFile 转 File
    public static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File convertedFile = new File(multipartFile.getOriginalFilename());
        try (FileOutputStream fos = new FileOutputStream(convertedFile)) {
            fos.write(multipartFile.getBytes());
        }
        return convertedFile;
    }

    public static MultipartFile setWaterMark(MultipartFile file,String fileName) throws IOException {
        InputStream watermarkStream = ImageUtil.class.getResourceAsStream("/static/watermark.png");
        BufferedImage watermarkImageBuffer = ImageIO.read(watermarkStream);

        BufferedImage originalImage = ImageIO.read(file.getInputStream());
        double originalwidth = originalImage.getWidth();
        double originalheight= originalImage.getHeight();
        int watermarkWidth;
        int watermarkHeight;
        if (originalwidth<originalheight) {
             watermarkWidth = (int) (originalwidth * 0.5 * 0.3);
             watermarkHeight = (int) ((originalwidth  / originalheight)*originalheight*0.5*0.3);
        }else {
            watermarkHeight = (int) (originalheight * 0.5 * 0.3);
            watermarkWidth = (int) ((originalheight / originalwidth)*originalwidth* 0.5 * 0.3);
        }
        Image watermarkImage = watermarkImageBuffer.getScaledInstance(watermarkWidth, watermarkHeight, Image.SCALE_SMOOTH);

        // 创建一个 BufferedImage
        BufferedImage watermark = new BufferedImage(
                watermarkImage.getWidth(null),
                watermarkImage.getHeight(null),
                BufferedImage.TYPE_INT_ARGB
        );

        // 获取 Graphics2D 对象并绘制图像
        java.awt.Graphics2D g2 = watermark.createGraphics();
        g2.drawImage(watermarkImage, 0, 0, null);
        g2.dispose();

        BufferedImage watermarkedImage = Thumbnails.of(originalImage)
                .size((int) (originalwidth * 0.5), (int) (originalheight * 0.5))
                .watermark(Positions.CENTER, watermark, 0.8f)
                .watermark(Positions.TOP_RIGHT, watermark, 0.8f)
                .watermark(Positions.BOTTOM_LEFT, watermark, 0.8f)
                .asBufferedImage();

        byte[] watermarkedBytes = bufferedImageToByteArray(watermarkedImage, "jpg");

        return new CustomMultipartFile(watermarkedBytes, fileName+".jpg", "image/jpg");
    }

    public static byte[] bufferedImageToByteArray(BufferedImage bufferedImage, String formatName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, formatName, baos);
        return baos.toByteArray();
    }


}
